import React, { useEffect, useState } from 'react';
import useImmer from '../../hooks/useImmer';
import { dayNameList, monthNameList } from './assets';
import styled from '@emotion/styled';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';

export default function Calendar() {
    /**
 * 最小年份
 */
    const MIN_YEAR = 1900;
    /**
 * 最大年份
 */
    const MAX_YEAR = 9999;

    /**
 * 目标日期
 */
    const [ targetDate, setTargetDate ] = useState<Date | null >(new Date());
    /**

    /**
 * 日历的各项属性
 */
    const state :Calandar.CalendarProps = {
        target: {
            year: null,
            month: null,
            date: null,
            day: null,
            monthShortName: null,
            monthFullName: null,
            monthChineseFullName: null,
            firstDay: null,
            firstDayIndex: null,
            totalDays: null,
            flag:true
        },
        previous: {
            totalDays: null,
        },
    };
    const [ calendarProps, setCalendarProps ] = useImmer(state);
    const [ calendarData, setCalendarData ] = useState<Calandar.RowDataType[][]>([]);
    const [ calendarFullName, setCalendarFullName ] = useState<string>('');
    /**
 * 用于展现的日历数据
 */
    const updateCalendarProps = ()=> {
        // 获取目标日期的年月日星期几数据
        let year = targetDate!.getFullYear();
        let month = targetDate!.getMonth();
        let date = targetDate!.getDate();
        let day = targetDate!.getDay();
        setCalendarProps((draf)=>{
            draf.target.year = year;
            draf.target.month = month;
            draf.target.date = date;
            draf.target.day = day;
        });
        console.log(targetDate, '----');
    };

    const updateCalendarData = ()=>{
        if(!calendarProps.target.firstDayIndex) return;
        let date = 1;
        const originalData = [];
        const firstRow = [];
        for (let i = 0; i <= 6; i++) {
            if(i < calendarProps.target.firstDayIndex!){
                const previousDate = calendarProps.previous.totalDays! - calendarProps.target.firstDayIndex! + (i+1);
                firstRow.push({
                    dateObj: new Date(
                        calendarProps.target.year!,
                        calendarProps.target.month! - 1,
                        previousDate
                    ),
                    dateNumber: previousDate,
                    dateType: "previous"
                });
            }else{
                firstRow.push({
                    dateObj: new Date(
                        calendarProps.target.year!,
                        calendarProps.target.month!,
                        date
                    ),
                    dateNumber: date,
                    dateType: "current"
                });
                date++;
            }
        }
        originalData.push(firstRow);
        for (let j = 0; j <=4; j++) {
            const rowData = [];
            for (let k = 0; k <=6; k++) {
                if(date <= calendarProps.target.totalDays!){
                    rowData.push({
                        dateObj: new Date(
                        calendarProps.target.year!,
                        calendarProps.target.month! + 1,
                        date
                        ),
                        dateNumber: date,
                        dateType: "current"
                    });
                }
                else {
                    // 设置目标月份下个月的日期数据
                    const nextDate = date - calendarProps.target.totalDays!;
                    rowData.push({
                        dateObj: new Date(
                            calendarProps.target.year!,
                            calendarProps.target.month! + 1,
                            nextDate
                        ),
                        dateNumber: nextDate,
                        dateType: "next"
                    });
                }
                date++;
            }
            originalData.push(rowData);
        }
        console.log(originalData, 'originalData');
        setCalendarData([ ...originalData ]);
    };
    useEffect(()=>{
        console.log(calendarProps, 'calendarProps');
        updateCalendarProps();
        const fullName = `${calendarProps.target.year!}年${calendarProps.target.month!+1}月`;
        setCalendarFullName(fullName);
    }, [ targetDate, calendarProps.target ]);

    useEffect(()=>{
        if(!calendarProps.target.year) return; 
        if (
            calendarProps.target.year! < MIN_YEAR ||
            calendarProps.target.year! > MAX_YEAR
        ) {
            console.log(targetDate, 'targetDatetargetDate');
            console.log(calendarProps.target.year!, 'calendarProps.target.year!');
            console.error("无效的年份，请检查传入的数据是否是正常");
            return;
        }

        // 获取到目标日期的月份【中文】名称
        let dateString:string[];
        dateString = targetDate!.toString().split(" ");
        // 获取目标月份的第一天是星期几，和在星期几中的索引值
        const targetMonthFirstDay = new Date(
            calendarProps.target.year!,
            calendarProps.target.month!,
            1
        );
        // 获取目标月份总共多少天
        const targetMonthLastDay = new Date(
            calendarProps.target.year!,
            calendarProps.target.month! + 1,
            0
        );

        // 获取目标月份的上个月总共多少天
        const previousMonth = new Date(
            calendarProps.target.year!,
            calendarProps.target.month!,
            0
        );
        setCalendarProps((draf)=>{
            draf.target.monthShortName = dateString[1];
            draf.target.monthFullName = monthNameList.fullName[draf.target.month!];
            draf.target.monthChineseFullName = monthNameList.chineseFullName[draf.target.month!];
            draf.target.firstDay! = targetMonthFirstDay.getDay();
            draf.target.firstDayIndex = dayNameList.findIndex(
                (day) => day.dayNumber === draf.target.firstDay
            );
            draf.target.totalDays = targetMonthLastDay.getDate();
            draf.previous.totalDays = previousMonth.getDate();
        });
    }, [ calendarProps.target.year, calendarProps.target.month! ]);

    useEffect(()=>{
        updateCalendarData();
    }, [ calendarProps.target.firstDayIndex ]);

    const jumpMonth = (flag: number) => {
        // flag 1 下一个月 -1 上一个月
        // 写一个函数，用于跳转到下一个月或者上一个月
        setCalendarProps((draf)=>{
            draf.target.month! += flag;
            if(draf.target.month! > 11){
                draf.target.year! += 1;
                draf.target.month! = 0;
            }else if(draf.target.month! < 0){
                draf.target.year! -= 1;
                draf.target.month! = 11;
            }
            setTargetDate(new Date(draf.target.year!, draf.target.month!, draf.target.date!));
        });
    };
    const isCurrentDay = (col) => {
        const currentMonth = new Date().getMonth() +1;
        const currentYear = new Date().getFullYear();
        const currentDate = new Date().getDate();
        const month = new Date(col.dateObj).getMonth();
        const year = new Date(col.dateObj).getFullYear();
        const date = new Date(col.dateObj).getDate();
        return currentMonth === month && currentYear === year && currentDate === date;
    };
    return (
        <Container>
            <Header>
                <LeftOutlined onClick={()=>jumpMonth(-1)} className='icon'/>
                <span>{calendarFullName}</span>
                <RightOutlined onClick={()=>jumpMonth(1)} className='icon'/>
            </Header>
           
            <Row>
                    
                {
                    dayNameList.map((day, index)=><Col key={index} index={index}>{day.chineseShortName}</Col>)
               
                }
            </Row>

            {
                calendarData.map((calendar, index)=>
                    <Row index={index} key={index + 'calendar'}>
                        {
                            calendar.map((col, colIndex)=><Col isCurrentDay={isCurrentDay(col)} index={colIndex} key={colIndex + 'col'}>{col.dateNumber}</Col>)
                        }
                    </Row>
                )
            }
        </Container>
    );
}
const Container = styled.div`
    border: 1px solid #ccc;
    width: 300px;
     -webkit-user-select: none; /* Safari */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* IE 10+ */
    user-select: none; /* 标准语法 */
`;

const Header = styled.div`
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 10px;
    & > .icon{
        &:focus{
            outline: none;
        }
    }
`;
const Row = styled.div<{index?:number}>`
    background-color: white;
    text-align: center;
    width: 100%;
    display: flex;
`;

const Col = styled.span<{index?:number, isCurrentDay?:boolean}>`
    padding: 12px;
    text-align: center;
    flex: 1;
    box-sizing: content-box;
    border-radius: 50%;

    &:hover{
        background-color: pink;
        color:white;
    }
    background:${props=>props.isCurrentDay ? 'pink' : 'transparent'}
`;
